package com.gallery.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gallery.mapper.ILoveImagesMapper;
import com.gallery.mapper.ImagesMapper;
import com.gallery.mapper.LogImagesMapper;
import com.gallery.mapper.UserMapper;
import com.gallery.service.IImagesService;
import com.gallery.service.ILoveImagesService;
import dto.PageDTO;
import entity.Images;
import entity.LogImages;
import entity.LoveImages;
import entity.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import query.ImagesQuery;
import vo.ImagesVO;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @param
 * @return
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class IImagesServiceImpl extends ServiceImpl<ImagesMapper, Images> implements IImagesService {
    private final ImagesMapper imagesMapper;
    private final ILoveImagesService iLoveImagesService;
    private final LogImagesServiceImpl logImagesService;
    private final LogImagesMapper logImagesMapper;
    private final ILoveImagesMapper iLoveImagesMapper;
    private final UserMapper userMapper;

    @Override
    public PageDTO<ImagesVO> querypage(ImagesQuery imagesQuery) {
        Long userId = StpUtil.getLoginIdAsLong();
        //PageDTO<ImagesVO> imagesVoPageDTO = PageUtil.page(imagesQuery,userId);
        LocalDateTime minlocalDateTime = null;
        LocalDateTime maxlocalDateTime = null;

        String name = imagesQuery.getName();
        String clazz = imagesQuery.getClazz();
        String status = imagesQuery.getStatus();
        LocalDate uploadTime = imagesQuery.getUploadTime();
        if (uploadTime != null){
            minlocalDateTime  = uploadTime.atTime(0,0,0);
            maxlocalDateTime = uploadTime.atTime(23,59,59);
        }

        //构建分页条件
        Page<Images> page = Page.of(imagesQuery.getPageNo(),imagesQuery.getPageSize());
        //构建排序条件
        if (StrUtil.isNotBlank(imagesQuery.getSortBy())){
            //如果以dayhot进行排序需先将该用户下所有照片当天的dayhot查询出来
            if (imagesQuery.getSortBy().equals("day_hot")){
                List<Images> images = imagesMapper
                        .selectList(new LambdaQueryWrapper<Images>()
                                .eq(Images::getUserId, userId));
                for (Images image : images) {
                    LambdaQueryWrapper<LogImages> wrapper = new LambdaQueryWrapper<LogImages>()
                            .ge(LogImages::getCreateTime, minlocalDateTime)
                            .le(LogImages::getCreateTime, maxlocalDateTime)
                            .eq(LogImages::getImagesId, image.getId());
                    int count = logImagesService.count(wrapper);
                    LambdaUpdateWrapper<Images> updateWrapper = new LambdaUpdateWrapper<Images>()
                            .set(Images::getDayHot, count)
                            .eq(Images::getId, image.getId());
                    update(updateWrapper);
                }
            }
            page.addOrder(new OrderItem(imagesQuery.getSortBy(),imagesQuery.getIsAsc()));
        }else {
            page.addOrder(new OrderItem("upload_time",false));
        }
        //构建查询条件
        Page<Images> imagesPage = lambdaQuery()
                .like(name != null&&name!="", Images::getName, name)
                .eq(clazz != null&&clazz!="", Images::getClazz, clazz)
                .eq(status != null, Images::getStatus,status)
                .eq(userId != null, Images::getUserId,userId)
                .ge(uploadTime != null,Images::getUploadTime, minlocalDateTime)
                .le(uploadTime != null,Images::getUploadTime, maxlocalDateTime)
                .page(page);

        PageDTO<ImagesVO> imagesVoPageDTO = new PageDTO<>();
        imagesVoPageDTO.setTotal(imagesPage.getTotal());
        imagesVoPageDTO.setPages(imagesPage.getPages());
        List<Images> records = imagesPage.getRecords();
        //判断是否有数据
        if (CollUtil.isEmpty(records)){
            imagesVoPageDTO.setList(Collections.emptyList());
            return imagesVoPageDTO;
        }
        List<ImagesVO> imagesVos = BeanUtil.copyToList(records, ImagesVO.class);
        //给imagevos赋值lovestatus
        int index=0;
        for (Images images:records){
            QueryWrapper<LoveImages>queryWrapper=new QueryWrapper<LoveImages>();
            queryWrapper.eq("user_id",userId)
                    .eq("images_id",images.getId());
            LoveImages images1 = iLoveImagesService.getOne(queryWrapper);
            if (ObjectUtil.isNotEmpty(images1)){
                imagesVos.get(index).setLoveStatus(1);
            }else {
                imagesVos.get(index).setLoveStatus(0);
            }
            index++;
        }
        imagesVoPageDTO.setList(imagesVos);
        return imagesVoPageDTO;
    }

    @Override
    public void upHot(Long imagesId) {

        UpdateWrapper<Images>updateWrapper=new UpdateWrapper<Images>();
        updateWrapper.setSql("all_hot=all_hot+1").eq("id",imagesId);
        imagesMapper.update(null,updateWrapper);
    }

    @Override
    public void deleteBatch(List<Long> ids) {
        Long userId = StpUtil.getLoginIdAsLong();
        for (Long id:ids){
            Long imagesId=id;
            //删除log表
            QueryWrapper<LogImages> logImagesQueryWrapper=new QueryWrapper<LogImages>();
            log.info("{}",imagesId);
            logImagesQueryWrapper.eq("user_id",userId).eq("images_id",imagesId);
            logImagesMapper.delete(logImagesQueryWrapper);
            //删除love表
            QueryWrapper<LoveImages> loveImagesQueryWrapper=new QueryWrapper<LoveImages>();
            loveImagesQueryWrapper.eq("user_id",userId).eq("images_id",imagesId);
            iLoveImagesMapper.delete(loveImagesQueryWrapper);
            //删除图片表
            QueryWrapper<Images> ImagesQueryWrapper=new QueryWrapper<Images>();
            ImagesQueryWrapper.eq("user_id",userId).eq("id",imagesId);
            imagesMapper.delete(ImagesQueryWrapper);
        }
    }

    @Override
    public List<ImagesVO> getRandoms() {

        return imagesMapper.randomImages();
    }

    @Override
    public List<ImagesVO> getRandomsByUser(Long userId) {
        //获取用户最常看的clazz
        QueryWrapper<Images> ImagesQueryWrapper=new QueryWrapper<Images>();
        ImagesQueryWrapper.select("clazz", "COUNT(*) AS count")
                .groupBy("clazz").orderByDesc("count");
        List<Images> images = imagesMapper.selectList(ImagesQueryWrapper);
        String clazz = images.get(0).getClazz();
        List<ImagesVO> imagesVOS = imagesMapper.randomImagesForUser(clazz);
        return imagesVOS;
    }

    @Override
    public List<String> getHotClazz() {

        QueryWrapper<Images> ImagesQueryWrapper=new QueryWrapper<Images>();
        ImagesQueryWrapper.select("clazz", "COUNT(*) AS count")
                .groupBy("clazz").orderByDesc("count").last("limit 10");
        List<Images> images = imagesMapper.selectList(ImagesQueryWrapper);
        List<String>list=new ArrayList<>();
        for(Images images1:images){
            list.add(images1.getClazz());
        }

        return list;
    }

    @Override
    public ImagesVO detailed(Long id) {
        Images images = imagesMapper.selectById(id);
        //查询当天照片的dayhot
        LocalDate localDate = LocalDate.now();
        LocalDateTime minlocalDateTime = localDate.atTime(0,0,0);
        LocalDateTime maxlocalDateTime = localDate.atTime(23,59,59);
        LambdaQueryWrapper<LogImages> wrapper = new LambdaQueryWrapper<LogImages>()
                .ge(LogImages::getCreateTime, minlocalDateTime)
                .le(LogImages::getCreateTime, maxlocalDateTime)
                .eq(LogImages::getImagesId, id);
        int count = logImagesService.count(wrapper);
        images.setDayHot((long) count);
        ImagesVO imagesVO = new ImagesVO();
        BeanUtil.copyProperties(images,imagesVO);
        //查询是否为喜欢照片
        LoveImages loveImages = iLoveImagesService.lambdaQuery()
                .eq(id != null, LoveImages::getImagesId, id).one();
        if (loveImages != null){
            imagesVO.setLoveStatus(1);
        }else {
            imagesVO.setLoveStatus(0);
        }
        User user = userMapper.selectById(images.getUserId());
        BeanUtil.copyProperties(user,imagesVO);
        return imagesVO;
    }

    @Override
    public List<Images>getall(Long userId) {
        List<Images> list = lambdaQuery().eq(Images::getUserId, userId).list();
        return list;
    }

    //TODO log表不知道是否能够redis分压，dayhot未写
    @Override
    public PageDTO<ImagesVO> getImageQuery(List<Images> images, ImagesQuery imagesQuery) {
        String sortBy = imagesQuery.getSortBy();
        //页数位置
        Long pageNo = imagesQuery.getPageNo();
        //每页大小
        Long pageSize = imagesQuery.getPageSize();
        long start=(pageNo-1)*pageSize;
        long end=Math.min(start+pageSize,images.size());
        //时降序排序
        if(sortBy.equals("upload_time")){
            images= images.stream().sorted(Comparator.comparing(Images::getUploadTime)
                    .reversed()).collect(Collectors.toList()).subList((int)start,(int)end);
        }else if(sortBy.equals("all_hot")){
            images=images.stream().sorted(Comparator.comparing(Images::getAllHot)
                    .reversed()).collect(Collectors.toList()).subList((int)start,(int)end);
        }
        //封装数据
        PageDTO<ImagesVO> imagesVoPageDTO = new PageDTO<>();
        List<ImagesVO> imagesVO=new ArrayList<>();
        //获取图片的喜欢信息
        for (Images images1:images){
            ImagesVO imagesVO1=new ImagesVO();
            BeanUtil.copyProperties(images1,imagesVO1);
            //查询love表喜欢
            QueryWrapper<LoveImages>queryWrapper=new QueryWrapper<LoveImages>();
            queryWrapper.eq("user_id",StpUtil.getLoginIdAsLong())
                    .eq("images_id",images1.getId());
            LoveImages imagesStatus = iLoveImagesService.getOne(queryWrapper);
            if (ObjectUtil.isNotEmpty(imagesStatus)){
                imagesVO1.setLoveStatus(1);
            }else {
                imagesVO1.setLoveStatus(0);
            }
            imagesVO.add(imagesVO1);
        }
        imagesVoPageDTO.setList(imagesVO);
        //总数量
        int size = images.size();
        //当前页面数据数目
        imagesVoPageDTO.setTotal((long) size);
        imagesVoPageDTO.setPages(pageNo);


        return imagesVoPageDTO;
    }
}
